package com.stationpc.dock

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.stationpc.dock.adapter.AppAdapter
import com.stationpc.dock.AppInfo
import android.provider.Settings
import android.net.Uri
import android.util.Log
import android.view.View
import com.stationpc.dock.service.DockOverlayService
import android.widget.ImageView

class SettingsActivity : AppCompatActivity() {

    private lateinit var appAdapter: AppAdapter
    private lateinit var recyclerView: RecyclerView
    private lateinit var saveButton: Button
    private lateinit var clearButton: Button
    private lateinit var toggleDockButton: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_settings)

        recyclerView = findViewById(R.id.appListRecyclerView)
        saveButton = findViewById(R.id.saveButton)
        clearButton = findViewById(R.id.clearButton)
        toggleDockButton = findViewById(R.id.toggleDockButton)

        setupRecyclerView()
        loadApps()
        setupSaveButton()
        setupClearButton()
        setupToggleDockButton()
    }

    private fun setupRecyclerView() {
        recyclerView.layoutManager = GridLayoutManager(this, 6)
        appAdapter = AppAdapter(
            onItemClick = { app ->
                app.isSelected = !app.isSelected
                appAdapter.notifyItemChanged(appAdapter.currentList.indexOf(app))
                updateCheckmarkVisibility(app)
            },
            onItemLongClick = { app ->
                openAppInfo(app.packageName)
            }
        )
        recyclerView.adapter = appAdapter
    }

    private fun loadApps() {
        val pm = packageManager
        val intent = Intent(Intent.ACTION_MAIN, null).apply {
            addCategory(Intent.CATEGORY_LAUNCHER)
        }

        val installedApps = pm.queryIntentActivities(intent, 0)
        val savedApps = getSavedApps()

        val appInfoList = installedApps.map { resolveInfo ->
            AppInfo(
                packageName = resolveInfo.activityInfo.packageName,
                name = resolveInfo.loadLabel(pm).toString(),
                icon = resolveInfo.loadIcon(pm),
                isSelected = savedApps.contains(resolveInfo.activityInfo.packageName)
            )
        }.sortedBy { it.name }

        appAdapter.submitList(appInfoList)
    }

    private fun updateCheckmarkVisibility(app: AppInfo) {
        val position = appAdapter.currentList.indexOf(app)
        if (position != -1) {
            val viewHolder = recyclerView.findViewHolderForAdapterPosition(position) as? AppAdapter.AppViewHolder
            viewHolder?.let {
                val checkmarkView = it.itemView.findViewById<ImageView>(R.id.checkmark)
                checkmarkView.visibility = if (app.isSelected) View.VISIBLE else View.GONE
            }
        }
    }

    private fun setupSaveButton() {
        saveButton.setOnClickListener {
            val selectedApps = appAdapter.currentList.filter { it.isSelected }.map { it.packageName }
            saveSelectedApps(selectedApps)
            Toast.makeText(this, getString(R.string.settings_saved), Toast.LENGTH_SHORT).show()
            toggleDockVisibility()
            finish()
        }
    }

    private fun setupClearButton() {
        clearButton.setOnClickListener {
            val updatedList = appAdapter.currentList.map { it.copy(isSelected = false) }
            appAdapter.submitList(updatedList)
        }
    }

    private fun setupToggleDockButton() {
        toggleDockButton.setOnClickListener {
            toggleDockVisibility()
        }
    }

    private fun saveSelectedApps(selectedApps: List<String>) {
        val sharedPrefs = getSharedPreferences("DockPrefs", MODE_PRIVATE)
        sharedPrefs.edit().putStringSet("selectedApps", selectedApps.toSet()).apply()
    }

    private fun getSavedApps(): Set<String> {
        val sharedPrefs = getSharedPreferences("DockPrefs", MODE_PRIVATE)
        return sharedPrefs.getStringSet("selectedApps", setOf()) ?: setOf()
    }

    private fun toggleDockVisibility() {
        val intent = Intent(this, DockOverlayService::class.java)
        intent.action = DockOverlayService.ACTION_TOGGLE_VISIBILITY
        startService(intent)
    }

    private fun openAppInfo(packageName: String) {
        try {
            val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                data = Uri.parse("package:$packageName")
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            startActivity(intent)
        } catch (e: Exception) {
            Log.e("SettingsActivity", "Unable to open app info: $packageName", e)
        }
    }
}
